<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, watch } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const fetchData = (query: any) => {
  // 根据路由参数执行你的逻辑，例如获取数据
  if (query.mainTopIndexNavigation) {
    const mainTopIndexNavigation = Array.isArray(query.mainTopIndexNavigation)
      ? query.mainTopIndexNavigation[0]
      : query.mainTopIndexNavigation;
    initTopMenu(mainTopIndexNavigation);
  } else {
    console.error("mainTopIndexNavigation 没进来");
  }
};

function initTopMenu(indexLocal: number) {
  if (indexLocal == props.index) {
    selected.value = true;
  }
}

// 立即执行一次 fetchData，并监听 route.query 的变化
watch(() => route.query, fetchData, { immediate: true });
///可以是一个html对象或者null对象
const contextArea = ref<HTMLElement | null>(null);
///控制菜单是否展示
const menuVisible = ref(false);
///控制子菜单是否展示
const subMenuVisible = ref(false);
///菜单的X坐标
const menuX = ref(0);
///菜单的Y坐标
const menuY = ref(0);
///子菜单的Y坐标
const subMenuY = ref(0);
///宽度自适应
const subMenuWidth = ref("auto");

///背景颜色的改变
const areBackgroundColor = ref({
  backgroundColor: "transparent",
});

const hideMenuTimeout = ref<ReturnType<typeof setTimeout> | null>(null);

///title 文本的文字  selected是否被选中 focus是否有焦点
const props = defineProps(["title", "showMenuControl", "selected", "index"]);

const showMenuControl = reactive([props.showMenuControl]);
const selected = ref(props.selected);

///绑定一菜单的基础样式
const subMenuStyle = ref({
  position: "absolute" as const,
  top: "0px",
  left: "100%",
  zIndex: 1000,
  backgroundColor: "#fff",
  border: "1px solid #ccc",
  boxShadow: "0 2px 10px rgba(0,0,0,0.2)",
  width: "auto",
});

const emit = defineEmits<{
  //定义一个回调方法，可以理解为回调父组件传入的attribute为ccc的方法，入参为一个number类型的变量
  (e: "ccc", parentName: String, name: String, type: number): void;
}>();

///钩子
onMounted(() => {
  toggleSelected(props.title);
});

function toggleSelected(name: String) {
  emit("ccc", props.title, name, 0);
}

function clickHandler(parentName: String, name: String) {
  areBackgroundColor.value = "#3C8DF9";
  emit("ccc", parentName, name, 1);
}

///显示子菜单
const showSubMenu = (event: MouseEvent, _item: string) => {
  const target = event.target as HTMLElement;
  const rect = target.getBoundingClientRect();
  subMenuY.value = rect.y;
  subMenuWidth.value = `${rect.width}px`;
  // subMenuStyle.value.left = `${rect.x}px`;
  subMenuStyle.value.top = `${30 * 3}px`;
  subMenuStyle.value.width = subMenuWidth.value;
  subMenuVisible.value = true;
};

watch(
  selected,
  (value) => {
    if (value) {
      areBackgroundColor.value = "#3C8DF9";
    } else {
      areBackgroundColor.value = "transparent";
    }
  },
  { immediate: true }
);

///菜单的样式
const menuStyle = ref({
  position: "absolute" as const,
  top: "0px",
  left: "0px",
  zIndex: 1000,
  backgroundColor: "#fff",
  border: "1px solid #ccc",
  textAlign: "left",
  boxShadow: "0 2px 10px rgba(0,0,0,0.2)",
  fontSize: "16px",
});

///菜单的的显示
const showMenu = (event: MouseEvent) => {
  ///禁止事件冒泡
  event.stopPropagation();
  if (contextArea.value) {
    const rect = contextArea.value.getBoundingClientRect();
    menuX.value = rect.x + 5;
    menuY.value = 60;
    menuStyle.value.left = `${menuX.value}px`;
    menuStyle.value.top = `${menuY.value}px`;
    menuVisible.value = true;
    if (!props.selected) {
      areBackgroundColor.value = "#9BC2F6";
    } else {
      areBackgroundColor.value = "#3C8DF9";
    }

    if (hideMenuTimeout.value) {
      clearTimeout(hideMenuTimeout.value);
      hideMenuTimeout.value = null;
    }
  }

  if (event.clientY <= 0) {
    hideMenu();
  }

  toggleSelected(props.title);
};

const handleMenuItemClick = (item: string) => {
  // alert(`点击了${item}`);
  menuVisible.value = false;
  subMenuVisible.value = false;
  emit("ccc", props.title, item, 1);
};

const hideSubMenu = (name: String) => {
  subMenuVisible.value = false;
};

const hideMenu = () => {
  if (hideMenuTimeout.value) {
    clearTimeout(hideMenuTimeout.value);
  }
  if (props.selected === false) {
    areBackgroundColor.value = "transparent";
  }
  menuVisible.value = false;
  subMenuVisible.value = false;
  // hideMenuTimeout.value = setTimeout(() => {
  //   menuVisible.value = false;
  //   subMenuVisible.value = false;
  //
  // }, 200); // Adjust the delay as needed
};

const handleClickOutside = (event: MouseEvent) => {
  // const target = event.target as HTMLElement;
  // if (contextArea.value && !contextArea.value.contains(target)) {
  //   hideMenu();
  // }
  // console.log(`krcm110${props.title}____${props.showMenuControl}`)
  if (props.showMenuControl === false) {
    hideMenu();
  }
};

onMounted(() => {
  window.addEventListener("mousemove", handleClickOutside);
});

onUnmounted(() => {
  window.removeEventListener("mousemove", handleClickOutside);
});
</script>

<template>
  <!--绑定contextArea-->
  <div
    ref="contextArea"
    :style="{ backgroundColor: areBackgroundColor }"
    @mouseenter="showMenu($event)"
    @mouseleave="hideMenu()"
    @click="clickHandler(props.title, props.title)"
    :class="{ selected_style: props.selected }"
    class="context-area"
  >
    {{ props.title }}

    <!--淡入效果-->
    <transition name="fade">
      <!--mouseleave监听鼠标移出的事件-->
      <div
        v-if="menuVisible"
        :style="menuStyle"
        class="menu"
        @mouseleave="hideMenu"
        @click.stop
      >
        <div
          style="font-size: 16px; font-weight: bold; padding: 8px 12px; color: #1a1a1a"
        >
          学习路线
        </div>
        <div class="menu-item" @click="handleMenuItemClick('培训任务学习')">
          培训任务学习>>
        </div>
        <div class="menu-item" @click="handleMenuItemClick('个人职业生命学习')">
          个人职业生命学习>>
        </div>
        <div
          class="menu-item"
          @mouseenter="showSubMenu($event, '学习资源')"
          @mouseleave="hideSubMenu('子')"
        >
          学习资源..
          <transition name="fade">
            <div v-if="subMenuVisible" :style="subMenuStyle" class="sub-menu" @click.stop>
              <div class="menu-item" @click="handleMenuItemClick('题库资源')">
                题库资源>>
              </div>
              <div class="menu-item" @click="handleMenuItemClick('课件资源')">
                课件资源>>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.context-area {
  width: 150px;
  height: 30px;
  border-right: 1px solid rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 28px;
  font-weight: bold;
  background-color: transparent;
  color: rgba(255, 255, 255, 0.8);
  padding: 14px 0;
}
.selected_style {
  color: white;
}

.childStyle {
  color: #ffffff;
  display: flex;
  align-items: center; /*垂直居中对齐*/
  gap: 15px; /* 添加元素之间的间距 */
}
.main {
  width: calc(100vw - 30px); /* 原始宽度减去 30px 的间距 */
  display: flex;
  justify-content: space-between;
  align-items: center; /*垂直居中对齐*/
  height: 64px;
  background: #004170;
}

.menu,
.sub-menu {
  position: absolute;
  background-color: #fff;
  border: 1px solid #ccc;
  z-index: 1000;
  border-radius: 6px;
  box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25);
}

.menu-item {
  padding: 8px 12px;
  cursor: pointer;
  white-space: nowrap;
  font-size: 14px;
  color: #ababab;
}

.menu-item:hover {
  background-color: #f5f5f5;
  color: #0771ff;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
